import urllib2
import time

try:
    import json
except ImportError:
    import simplejson as json

J = json.JSONDecoder()

class Stress1:
    def __init__(self, server='http://127.0.0.1:5000'):
        self.server = server

    def execute(self, input):
        return urllib2.urlopen('%s/execute?input=%s'%(self.server, urllib2.quote(input))).read()

    def get(self, id):
        return J.decode(urllib2.urlopen('%s/get?id=%s'%(self.server,urllib2.quote(id))).read())
        
    def test1(self, input='2+2', wait=0):
        id = self.execute(input)
        while True:
            z = self.get(id)
            if z['status'] == 'done':
                return z
            else:
                time.sleep(wait)

    def test2(self, n=100, input='2+2'):
        """
        How long does it take to submit n tasks in serial?
        """
        for i in range(n):
            self.execute(input)
        
    def test3(self, n=100, input='2+2', wait=0):
        """
        How long does it take to submit n tasks in serial, then wait
        until all report a status of done.
        """
        ids = []
        for i in range(n):
            ids.append(self.execute(input))
        k = 0
        while len(ids) > 0:
            for id in list(ids):
                if self.get(id)['status'] == 'done':
                    ids.remove(id)
                else:
                    time.sleep(wait)
                    print "waiting..."
                    k += 1
        return k

    def test4(self, n=100):
        """
        Grab a static page n times.
        """
        for i in range(n):
            urllib2.urlopen('%s/static/static.html'%self.server).read()

        
        
        
                
        
